﻿
Imports System.Threading
Imports osi.root.connector
Imports osi.root.constants
Imports osi.root.utils
Imports osi.root.delegates
Imports tp = System.Threading.ThreadPool

Public Class managed_threadpool
    Inherits threadpool

    Private Sub New(Optional ByVal thread_count As Int64 = npos)
        MyBase.New()
        If thread_count <= 0 Then
            thread_count = default_thread_count()
        End If
        Me.thread_count() = thread_count
    End Sub

    Public Overrides Property thread_count As Int32
        Get
            Dim ft As Int32 = 0
            Dim bt As Int32 = 0
            tp.GetMaxThreads(ft, bt)
            Return ft + bt
        End Get
        Set(ByVal value As Int32)
            tp.SetMaxThreads(value >> 1, value >> 1)
        End Set
    End Property

    Protected Overrides Function managed_threads() As Thread()
        Return Nothing
    End Function

    Protected Overloads Overrides Sub queue_job(ByVal wi As work_info)
        queue_in_managed_threadpool(AddressOf work_on, wi)
    End Sub

    Public Shared ReadOnly [global] As managed_threadpool = Nothing

    Shared Sub New()
        [global] = New managed_threadpool()
    End Sub

    Public Overloads Shared Sub register()
        threadpool.register([global])
    End Sub
End Class
